package com.suyun.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.JSONUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ExceptionHandlerPag implements UrlBlockHandler {
    ResponseData responseData = null;

    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        if(e instanceof FlowException){
            responseData =  new ResponseData(1,"限流了");
        }else if (e instanceof DegradeException){
            responseData= new ResponseData(2,"降级了");
        }
        response.getWriter().write(JSON.toJSONString(responseData));
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class ResponseData {
    private Integer code;
    private String message;
}
